package dao.impl;
import dao.IDVDDao;
import entity.DVD;

public class DVDDaoImpl implements IDVDDao{
	private DVD[] manyDVD;
	
	public DVDDaoImpl(){
		manyDVD = new DVD[20];
	}
	
	private int getUseFulIndex(){
		for (int i = 0; i < manyDVD.length; i++) {
			if(manyDVD[i] == null){
				return i;
			}
		}
		return manyDVD.length;
	}
	
	@Override
	public boolean save(DVD dvd) {
		int index = getUseFulIndex();
		if(selectByName(dvd.getDvdName()) != null){
			return false;
		}
		if (index != manyDVD.length) {
			manyDVD[index] = dvd;
			return true;
		}
		return false;
	}

	@Override
	public boolean delete(String name) {
		int index = getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if(manyDVD[i].getDvdName().equals(name)){
				for (int j = i; j < index-1; j++) {
					manyDVD[j] = manyDVD[j+1];
				}
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean update(DVD dvd) {
		return false;
	}

	@Override
	public DVD selectByName(String name) {
		int index = getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if(manyDVD[i].getDvdName().equals(name)){
				return manyDVD[i];
			}
		}
		return null;
	}

	@Override
	public DVD[] selectByType(String type) {
		int index = getUseFulIndex();
		DVD[] sameDVDType = new DVD[manyDVD.length];
		for (int i = 0,j = 0; i < index; i++) {
			if(manyDVD[i].getDvdType().equals(type)){
				sameDVDType[j++] = manyDVD[i];
			}
		}
		return sameDVDType;
	}

	@Override
	public DVD[] selectAll() {
		return manyDVD;
	}

	@Override
	public boolean rentDVD(String name) {
		int index = getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if(manyDVD[i].equals(name) && !manyDVD[i].isRent()){
				manyDVD[i].setRent(true);
				manyDVD[i].setTime(manyDVD[i].getTime()+1);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean returnDVD(String name) {
		int index = getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if(manyDVD[i].getDvdName().equals(name) && manyDVD[i].isRent()){
				manyDVD[i].setRent(false);
				return true;
			}
		}
		return false;
	}

	@Override
	public DVD[] selectAllNotRend() {
		int index = getUseFulIndex();
		DVD[] notRendDVD = new DVD[manyDVD.length];
		for (int i = 0,j = 0; i < index; i++) {
			if(!manyDVD[i].isRent()){
				notRendDVD[j++] = manyDVD[i];
			}
		}
		return notRendDVD;
	}

	@Override
	public DVD[] descendingOrderByTime() {
		int index = getUseFulIndex();
		DVD[] dvdSortByTime = new DVD[manyDVD.length];
		System.arraycopy(manyDVD, 0, dvdSortByTime, 0, index);
		for (int i = 0; i < index - 1; i++) {
			for (int j = 0; j < index - 1 - i; j++) {
				if(dvdSortByTime[j].getTime() < dvdSortByTime[j+1].getTime()){
					DVD temp = dvdSortByTime[j];
					dvdSortByTime[j] = dvdSortByTime[j+1];
					dvdSortByTime[j+1] = temp;
				}
			}
		}
		return dvdSortByTime;
	}

}
